import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import json
import os
from pypinyin import lazy_pinyin, Style
import threading
import time
from tkinter import font

class PoetryReader:
    def __init__(self, root):
        self.root = root
        self.root.title("古诗词跟读器")
        self.root.geometry("800x600")
        
        # 默认设置
        self.settings = {
            "font_family": "Microsoft YaHei",
            "font_size": 24,
            "text_color": "#2C3E50",
            "highlight_color": "#E74C3C",
            "bg_color": "#F8F9FA",
            "bg_image": None,
            "reading_speed": 1.0,  # 速度倍数
            "window_opacity": 0.9,
            "show_pinyin": True
        }
        
        # 当前诗词数据
        self.current_poetry = {
            "title": "静夜思",
            "author": "李白",
            "content": [
                "床前明月光",
                "疑是地上霜",
                "举头望明月",
                "低头思故乡"
            ]
        }
        
        self.is_reading = False
        self.current_line = 0
        self.current_char = 0
        
        self.setup_ui()
        self.load_settings()
        
    def setup_ui(self):
        """设置界面"""
        # 创建主框架
        self.main_frame = ttk.Frame(self.root, style="Main.TFrame")
        self.main_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)
        
        # 标题区域
        self.title_frame = ttk.Frame(self.main_frame)
        self.title_frame.pack(fill=tk.X, pady=(0, 20))
        
        self.title_label = ttk.Label(
            self.title_frame, 
            text=f"{self.current_poetry['title']} - {self.current_poetry['author']}",
            font=(self.settings["font_family"], self.settings["font_size"] + 8, "bold"),
            foreground=self.settings["text_color"]
        )
        self.title_label.pack()
        
        # 诗词显示区域
        self.text_frame = ttk.Frame(self.main_frame)
        self.text_frame.pack(fill=tk.BOTH, expand=True, pady=(0, 20))
        
        self.text_widgets = []
        self.pinyin_widgets = []
        
        for i, line in enumerate(self.current_poetry["content"]):
            # 创建文本标签
            text_label = ttk.Label(
                self.text_frame,
                text=line,
                font=(self.settings["font_family"], self.settings["font_size"]),
                foreground=self.settings["text_color"],
                background=self.settings["bg_color"]
            )
            text_label.pack(pady=5)
            self.text_widgets.append(text_label)
            
            # 创建拼音标签
            if self.settings["show_pinyin"]:
                pinyin_text = " ".join(lazy_pinyin(line, style=Style.TONE))
                pinyin_label = ttk.Label(
                    self.text_frame,
                    text=pinyin_text,
                    font=(self.settings["font_family"], self.settings["font_size"] - 8),
                    foreground=self.settings["text_color"],
                    background=self.settings["bg_color"]
                )
                pinyin_label.pack()
                self.pinyin_widgets.append(pinyin_label)
        
        # 控制按钮区域
        self.control_frame = ttk.Frame(self.main_frame)
        self.control_frame.pack(fill=tk.X)
        
        self.start_button = ttk.Button(
            self.control_frame,
            text="开始跟读",
            command=self.start_reading
        )
        self.start_button.pack(side=tk.LEFT, padx=5)
        
        self.stop_button = ttk.Button(
            self.control_frame,
            text="停止跟读",
            command=self.stop_reading,
            state=tk.DISABLED
        )
        self.stop_button.pack(side=tk.LEFT, padx=5)
        
        self.settings_button = ttk.Button(
            self.control_frame,
            text="设置",
            command=self.open_settings
        )
        self.settings_button.pack(side=tk.LEFT, padx=5)
        
        # 速度控制
        speed_frame = ttk.Frame(self.control_frame)
        speed_frame.pack(side=tk.RIGHT, padx=5)
        
        ttk.Label(speed_frame, text="速度:").pack(side=tk.LEFT)
        self.speed_scale = ttk.Scale(
            speed_frame,
            from_=0.5,
            to=2.0,
            value=self.settings["reading_speed"],
            command=self.update_speed
        )
        self.speed_scale.pack(side=tk.LEFT, padx=5)
        
        self.speed_label = ttk.Label(speed_frame, text=f"{self.settings['reading_speed']:.1f}x")
        self.speed_label.pack(side=tk.LEFT)
        
        # 配置样式
        self.setup_styles()
        
    def setup_styles(self):
        """设置样式"""
        style = ttk.Style()
        
        # 配置主框架样式
        style.configure(
            "Main.TFrame",
            background=self.settings["bg_color"]
        )
        
        # 配置标签背景
        for widget in self.text_widgets + self.pinyin_widgets:
            widget.configure(background=self.settings["bg_color"])
    
    def start_reading(self):
        """开始跟读"""
        if not self.is_reading:
            self.is_reading = True
            self.start_button.config(state=tk.DISABLED)
            self.stop_button.config(state=tk.NORMAL)
            
            # 重置位置
            self.current_line = 0
            self.current_char = 0
            
            # 创建跟读线程
            self.reading_thread = threading.Thread(target=self.reading_process)
            self.reading_thread.daemon = True
            self.reading_thread.start()
    
    def stop_reading(self):
        """停止跟读"""
        self.is_reading = False
        self.start_button.config(state=tk.NORMAL)
        self.stop_button.config(state=tk.DISABLED)
        
        # 重置所有文本颜色
        for widget in self.text_widgets:
            widget.configure(foreground=self.settings["text_color"])
    
    def reading_process(self):
        """跟读过程"""
        try:
            for line_idx, line in enumerate(self.current_poetry["content"]):
                if not self.is_reading:
                    break
                
                self.current_line = line_idx
                chars = list(line)
                
                # 重置当前行颜色
                self.text_widgets[line_idx].configure(foreground=self.settings["text_color"])
                
                for char_idx, char in enumerate(chars):
                    if not self.is_reading:
                        break
                    
                    self.current_char = char_idx
                    
                    # 更新UI（在主线程中）
                    self.root.after(0, self.highlight_character, line_idx, char_idx)
                    
                    # 根据速度等待
                    time.sleep(0.5 / self.settings["reading_speed"])
                
                # 行结束，标记整行为高亮
                if self.is_reading:
                    self.root.after(0, self.highlight_line, line_idx)
                    time.sleep(1.0 / self.settings["reading_speed"])
            
            # 跟读完成
            if self.is_reading:
                self.root.after(0, self.reading_complete)
                
        except Exception as e:
            self.root.after(0, lambda: messagebox.showerror("错误", f"跟读过程中出现错误: {str(e)}"))
    
    def highlight_character(self, line_idx, char_idx):
        """高亮字符"""
        line = self.current_poetry["content"][line_idx]
        chars = list(line)
        
        # 创建带高亮的文本
        highlighted_text = ""
        for i, char in enumerate(chars):
            if i <= char_idx:
                highlighted_text += char
            else:
                highlighted_text += char
        
        # 更新标签文本和颜色
        self.text_widgets[line_idx].configure(
            text=highlighted_text,
            foreground=self.settings["highlight_color"]
        )
    
    def highlight_line(self, line_idx):
        """高亮整行"""
        self.text_widgets[line_idx].configure(foreground=self.settings["highlight_color"])
    
    def reading_complete(self):
        """跟读完成"""
        self.is_reading = False
        self.start_button.config(state=tk.NORMAL)
        self.stop_button.config(state=tk.DISABLED)
        messagebox.showinfo("完成", "跟读完成！")
    
    def update_speed(self, value):
        """更新速度"""
        self.settings["reading_speed"] = float(value)
        self.speed_label.config(text=f"{float(value):.1f}x")
    
    def open_settings(self):
        """打开设置窗口"""
        settings_window = tk.Toplevel(self.root)
        settings_window.title("设置")
        settings_window.geometry("400x500")
        
        # 字体设置
        font_frame = ttk.LabelFrame(settings_window, text="字体设置", padding=10)
        font_frame.pack(fill=tk.X, padx=10, pady=5)
        
        ttk.Label(font_frame, text="字体:").grid(row=0, column=0, sticky=tk.W)
        font_family_var = tk.StringVar(value=self.settings["font_family"])
        font_combo = ttk.Combobox(font_frame, textvariable=font_family_var, values=font.families())
        font_combo.grid(row=0, column=1, padx=5)
        
        ttk.Label(font_frame, text="字号:").grid(row=1, column=0, sticky=tk.W, pady=5)
        font_size_var = tk.IntVar(value=self.settings["font_size"])
        font_size_spin = ttk.Spinbox(font_frame, from_=12, to=48, textvariable=font_size_var)
        font_size_spin.grid(row=1, column=1, padx=5)
        
        # 颜色设置
        color_frame = ttk.LabelFrame(settings_window, text="颜色设置", padding=10)
        color_frame.pack(fill=tk.X, padx=10, pady=5)
        
        ttk.Label(color_frame, text="文字颜色:").grid(row=0, column=0, sticky=tk.W)
        text_color_btn = tk.Button(color_frame, bg=self.settings["text_color"], width=10)
        text_color_btn.grid(row=0, column=1, padx=5)
        
        ttk.Label(color_frame, text="高亮颜色:").grid(row=1, column=0, sticky=tk.W, pady=5)
        highlight_color_btn = tk.Button(color_frame, bg=self.settings["highlight_color"], width=10)
        highlight_color_btn.grid(row=1, column=1, padx=5)
        
        ttk.Label(color_frame, text="背景颜色:").grid(row=2, column=0, sticky=tk.W, pady=5)
        bg_color_btn = tk.Button(color_frame, bg=self.settings["bg_color"], width=10)
        bg_color_btn.grid(row=2, column=1, padx=5)
        
        # 其他设置
        other_frame = ttk.LabelFrame(settings_window, text="其他设置", padding=10)
        other_frame.pack(fill=tk.X, padx=10, pady=5)
        
        show_pinyin_var = tk.BooleanVar(value=self.settings["show_pinyin"])
        ttk.Checkbutton(other_frame, text="显示拼音", variable=show_pinyin_var).pack(anchor=tk.W)
        
        # 保存按钮
        def save_settings():
            self.settings["font_family"] = font_family_var.get()
            self.settings["font_size"] = font_size_var.get()
            self.settings["show_pinyin"] = show_pinyin_var.get()
            
            # 更新UI
            self.update_display()
            settings_window.destroy()
        
        ttk.Button(settings_window, text="保存", command=save_settings).pack(pady=10)
    
    def update_display(self):
        """更新显示"""
        # 更新标题
        self.title_label.config(
            font=(self.settings["font_family"], self.settings["font_size"] + 8, "bold"),
            foreground=self.settings["text_color"]
        )
        
        # 更新文本
        for i, line in enumerate(self.current_poetry["content"]):
            self.text_widgets[i].config(
                text=line,
                font=(self.settings["font_family"], self.settings["font_size"]),
                foreground=self.settings["text_color"]
            )
            
            # 更新拼音
            if i < len(self.pinyin_widgets):
                if self.settings["show_pinyin"]:
                    pinyin_text = " ".join(lazy_pinyin(line, style=Style.TONE))
                    self.pinyin_widgets[i].config(
                        text=pinyin_text,
                        font=(self.settings["font_family"], self.settings["font_size"] - 8),
                        foreground=self.settings["text_color"]
                    )
                    self.pinyin_widgets[i].pack()
                else:
                    self.pinyin_widgets[i].pack_forget()
    
    def load_settings(self):
        """加载设置"""
        # 这里可以添加从文件加载设置的代码
        pass
    
    def save_settings_to_file(self):
        """保存设置到文件"""
        # 这里可以添加保存设置到文件的代码
        pass

def main():
    root = tk.Tk()
    app = PoetryReader(root)
    root.mainloop()

if __name__ == "__main__":
    main()